import { GUI } from "dat.gui"
import { 
  AxesHelper,
  HemisphereLight,
  Mesh,
  MeshNormalMaterial,
  PerspectiveCamera, 
  Scene, 
  WebGLRenderer,
  Group,
  BoxGeometry,
  Geometry,
  ObjectLoader,
  Object3D
} from "three"
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import stats from '../utils/stats'

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
// 不能设置为0
camera.position.set(-3, 13, 39)

const renderer = new WebGLRenderer({ antialias: true })
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setClearColor(0xeeeeee)
renderer.setSize(window.innerWidth, window.innerHeight)

document.body.appendChild(renderer.domElement)

new OrbitControls(camera, renderer.domElement)

// 添加坐标系
const axes = new AxesHelper(100)
scene.add(axes)

const light = new HemisphereLight(0xffffff, 0xcccccc, 1)
scene.add(light)

const material = new MeshNormalMaterial({
  transparent: true,
  opacity: 0.5
})

let box: Mesh<Geometry>
let loadedMesh: Object3D

let controls = {
  width: 2,
  height: 2,
  depth: 2,

  draw() {
    scene.remove(box)

    const boxGeom = new BoxGeometry(this.width, this.height, this.depth)
    box = new Mesh(boxGeom, material)

    scene.add(box)
  },

  save() {
    let result = box.toJSON()
    localStorage.setItem('json', JSON.stringify(result))
    console.log(localStorage.getItem('json'))
  },

  load() {
    scene.remove(loadedMesh)

    let json = localStorage.getItem('json')

    if (json) {
      let loadGeom = JSON.parse(json)
      // 加载器
      let loader = new ObjectLoader()

      loadedMesh = loader.parse(loadGeom)
      loadedMesh.position.x -= 10
      scene.add(loadedMesh)
    }
  }
}

controls.draw()

const gui = new GUI()
const ioGUI = gui.addFolder('保存与加载')
ioGUI.add(controls, 'save').name('保存')
ioGUI.add(controls, 'load').name('加载')
ioGUI.open()

const boxGUI = gui.addFolder('矩形')
boxGUI.add(controls, 'width', 1, 10, 1).name('宽').onChange(controls.draw.bind(controls))
boxGUI.add(controls, 'height', 1, 10, 1).name('高').onChange(controls.draw.bind(controls))
boxGUI.add(controls, 'depth', 1, 10, 1).name('深').onChange(controls.draw.bind(controls))


function render(time: number): void {
  stats.update()

  box.rotation.x += 0.01
  box.rotation.y += 0.01

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}

requestAnimationFrame(render)